<template>
  <div class="profile-container">
    <div class="profile-card">
      <div class="card-header">
        <h3 class="header-title">个人中心</h3>
        <p class="header-subtitle">管理你的个人信息</p>
      </div>

      <el-form
          :model="user"
          :rules="rules"
          ref="userFormRef"
          label-position="left"
          label-width="120px"
          class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" disabled clearable size="large" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="user.password"
              type="password"
              show-password
              placeholder="留空则不修改"
              size="large"
          />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input
              v-model="user.phone"
              placeholder="请输入手机号码"
              clearable
              size="large"
          />
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number
              v-model.number="user.age"
              :min="1"
              :max="150"
              placeholder="请输入年龄"
              size="large"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item class="action-buttons">
          <el-button
              type="primary"
              @click="handleSave"
              :loading="isLoading"
              size="large"
              class="save-button"
          >
            {{ isLoading ? '保存中...' : '保存修改' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyProfile',
  data() {
    return {
      user: {
        username: '',
        password: '',
        phone: '',
        age: null
      },
      rules: {
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined) {
                callback(new Error('请输入年龄'));
              } else if (typeof value !== 'number') {
                callback(new Error('年龄必须为数字'));
              } else if (value < 1 || value > 150) {
                callback(new Error('年龄范围为1-150岁'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      isLoading: false
    };
  },
  created() {
    this.loadUserInfo();
  },
  methods: {
    handleSave() {
      this.isLoading = true;
      this.$refs.userFormRef.validate(valid => {
        if (valid) {
          this.$confirm('是否确认修改个人信息？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.updateProfile();
          }).catch(() => {
            this.isLoading = false;
            this.$message.info('已取消修改');
          });
        } else {
          this.$message.warning('请检查并修正表单中的错误');
          this.isLoading = false;
          return false;
        }
      });
    },
    loadUserInfo() {
      try {
        const storedUser = JSON.parse(localStorage.getItem('user'));
        if (storedUser) {
          if (storedUser.age !== null && storedUser.age !== undefined) {
            storedUser.age = Number(storedUser.age);
          }
          this.user = {
            ...this.user,
            ...storedUser
          };
        } else {
          this.resetToDefaultUser();
        }
      } catch (error) {
        console.error('解析用户信息出错:', error);
        this.$message.error('加载用户信息失败');
        this.resetToDefaultUser();
      }
    },
    resetToDefaultUser() {
      this.user = {
        username: '未登录',
        password: '',
        phone: '',
        age: null
      };
    },
    updateProfile() {
      const ageValue = this.user.age;
      if (ageValue === null || ageValue === undefined) {
        this.$message.error('请输入年龄');
        this.isLoading = false;
        return;
      }

      const num = Number(ageValue);
      if (isNaN(num) || num < 1 || num > 150) {
        this.$message.error('请输入1到150之间的有效年龄');
        this.isLoading = false;
        return;
      }

      const submitData = {
        ...this.user,
        age: String(num)
      };

      this.$request.post('/updateUser', submitData)
          .then(response => {
            if (response && response.code === 200) {
              localStorage.setItem('user', JSON.stringify(submitData));
              this.$message.success('个人信息已更新');
              this.loadUserInfo();
            } else {
              this.$message.error(response.message || '更新失败，请重试');
            }
          })
          .catch(error => {
            console.error('请求异常:', error);
            this.$message.error('网络请求失败');
          })
          .finally(() => {
            this.isLoading = false;
          });
    }
  }
};
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ecfa 100%);
  overflow: hidden; /* 禁止页面滚动 */
}

.profile-card {
  width: 100%;
  max-width: 600px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.profile-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.card-header {
  padding: 32px 32px 24px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: white;
}

.header-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.header-subtitle {
  margin: 8px 0 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.85);
}

.profile-form {
  padding: 32px;
}

.action-buttons {
  margin-top: 32px;
}

.save-button {
  height: 48px;
  width: 100%;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border: none;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;
}

.save-button:hover {
  background: linear-gradient(135deg, #3a8ee6 0%, #3071a9 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.save-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.4);
}

.el-form-item.is-error .el-input__inner {
  animation: shake 0.3s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}
</style>
